#coding=utf-8
#
# Copyright (C) 2014  NianNian TECH Co., Ltd. All rights reserved.
# Created on 2014-5-16, by Junn
# 
#

from functools import wraps

from django.core.urlresolvers import reverse
from django.shortcuts import redirect
from django.core.handlers.wsgi import WSGIRequest

from utils.http import JResponse
from core import codes


def member_required(func):
    pass

def validate_id(method, key=None):
    """
    validate the id named 'key' in request method
    """
    def _validate(func):
        def validate(obj, request=None, *args, **kwargs):
            if isinstance(obj, WSGIRequest):
                # for APIView and function view
                request = obj
            if request.method != method:
                # check method
                return JResponse(codes.get('invalid_request_method'))
            if key:
                if method == "POST":
                    arg = request.POST.get(key)
                elif method == "GET":
                    arg = request.GET.get(key)
                else:
                    return JResponse(codes.get('invalid_request_method'))
                try:
                    int(arg)
                except Exception, e:
                    print e
                    return JResponse(codes.get('params_error'))
            if obj == request:
                # for APIView and function view
                return func(request, *args, **kwargs)
            return func(obj, request, *args, **kwargs)
        return validate
    return _validate

